<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Constants\ErrorCode;
use App\Model\Admin\Admin;
use App\Model\ChargeDetail;
use App\Model\ChargeOption;
use App\Model\Device;
use App\Model\Station;
use Hyperf\Redis\Redis;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use Util\Common;
use App\Controller\AbstractController;

class ChargeOptionController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    #[Inject]
    protected ChargeOption $chargeOption;

    #[Inject]
    protected Admin $admin;

    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }

    /**套餐列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getList(RequestInterface $request): ResponseInterface
    {

        $page = $request->inputs(['page', 'limit', 'keyword', 'distributor_id', 'is_autoload', 'mode', 'type']);
        $info = $this->admin->getInfo($request);
        $query = $this->chargeOption->where(function ($query) use ($page,$info) {
            if (array_key_exists('keyword', $page) && $page['keyword']) {
                $query->where('name', 'like', '%' . $page['keyword'] . '%');
            }
            if ($page['type'] !== '') {
                $query->where('type', $page['type']);
            }
            if ($page['mode'] == 'pt') {
                $query->where('distributor_id', 0);
            } else {
                if ($page['distributor_id']) {
                    $query->where('distributor_id', $page['distributor_id']);
                } else {
                    if (isset($info['distributor_id'])) {
                        $query->where('distributor_id', $info['distributor_id']);
                    } else {
                        $query->where('distributor_id', '>', 0);
                    }
                }
            }
            if ($page['is_autoload'] !== '') {
                $query->where('is_autoload', $page['is_autoload']);
            }
            $query->where('is_del', 1);
        })->with('time_children', 'power_children', 'service_children')
            ->with(['distributor' => function ($query) {
                $query->select('id', 'name'); // 只获取经销商id和name
            }]);
        $data['total'] = $query->count();
        $data['list'] = $query->orderBy('sort', 'desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->get();
        return $this->success($data);
    }

    /**修改状态
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function changeStatus(RequestInterface $request)
    {
        $id = $request->input('id', 0, 'int');
        if (!$id) {
            return $this->error(ErrorCode::PARAMS_ERR);
        }
        $is_autoload = $request->input('is_autoload', 0, 'int');
        $charge_option = ChargeOption::find($id);
        $info = $this->admin->getInfo($request);
        if (isset($info['distributor_id']) && $info['distributor_id'] != $charge_option->distributor_id) {
            return $this->error(1001, '仅可删除自己名下套餐');
        }
        if (!$charge_option) {
            return $this->error(ErrorCode::PARAMS_ERR);
        }
        $charge_option->is_autoload = $is_autoload;
        $charge_option->save();
        return $this->success();
    }


    /**删除
     * @param RequestInterface $request
     * @return \Psr\Http\Message\ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function del(RequestInterface $request): \Psr\Http\Message\ResponseInterface
    {
        Db::beginTransaction();
        try {
            $id = $request->input('charge_option_id', 0, 'int');
            if (!$id) {
                return $this->error(ErrorCode::PARAMS_ERR);
            }
            $info = $this->admin->getInfo($request);
            $charge = $this->chargeOption->findOrFail($id);
            if (isset($info['distributor_id']) && $info['distributor_id'] != $charge->distributor_id) {
                return $this->error(1001, '仅可删除自己名下套餐');
            }
            $charge->is_del = 0;
            $charge->save();
            ChargeDetail::where('charge_option_id', $id)->update(['is_del' => 0]);
            Station::where('charge_id', $id)->update(['charge_id' => 0]);
            Db::commit();
            return $this->success();
        } catch (\Exception $e) {
            Db::rollBack();
            return $this->error(code: 1001, msg:$e->getMessage().$e->getTraceAsString());
        }
    }


    public function getAll(RequestInterface $request){
        $distributor_id = $request->input('distributor_id', 0, 'int');
        $info = $this->admin->getInfo($request);
        if($info['type'] != Admin::TYPE_USER && !$distributor_id){
            return $this->error(1001, '请选择经销商');
        }else{
            if(!$distributor_id){
                $distributor_id = $info['distributor_id'];
            }
        }
        $data = $this->chargeOption
            ->where(function ($query) use ($info,$distributor_id) {
                if($distributor_id){
                    $query->where('distributor_id', $distributor_id)
                        ->orWhere('distributor_id', 0);
                }
            })
            ->where('is_del', 1)
            ->orderBy('distributor_id','asc')
            ->get();

        return $this->success($data);
    }


    /**
     * 创建/编辑
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function onceCreate(RequestInterface $request): ResponseInterface
    {
        $params = $request->inputs(['id', 'type', 'service_type', 'service_fee', 'min_price', 'service_children',
            'name', 'is_autoload', 'fee', 'power_children', 'time_children', 'elec_price', 'distributor_id']);
        if (!$params['name']) {
            return $this->error(code: 1002, msg: '套餐名称不能为空');
        }
        $info = $this->admin->getInfo($request);
        if (!isset($params['distributor_id'])) {
            if (isset($info['distributor_id'])) {
                $params['distributor_id'] = $info['distributor_id'];
            } else {
                $params['distributor_id'] = 0;
            }
        }
        Db::beginTransaction();
        try {
            $save['is_autoload'] = $params['is_autoload'];
            $save['name'] = $params['name'];
            $save['distributor_id'] = $params['distributor_id'];
            $save['min_price'] = $params['min_price'];
            $save['fee'] = $params['fee'];
            if ($params['type'] == ChargeDetail::SERVICE) {
                $save['service_type'] = $params['service_type'];
                $save['service_fee'] = $params['service_fee'];
                $save['elec_price'] = $params['elec_price'];
            }
            $save['type'] = $params['type'];
            $option = ChargeOption::create($save);
            $params['id'] = $option->id;
            if ($params['type'] == ChargeDetail::SERVICE && $params['service_type'] == 2) {
                if (isset($params['service_children'])) {
                    $params['service_children'] = json_decode($params['service_children'], true);
                    foreach ($params['service_children'] as $k => $v) {
                        $save = [];
                        $save['fee'] = $v['fee'];
                        $save['min_power'] = $v['min_power'];
                        $save['max_power'] = $v['max_power'];
                        $save['charge_option_id'] = $params['id'];
                        if(isset($v['minutes'])){
                            $save['minutes'] = $v['minutes'];
                        }
                        $save['type'] = ChargeDetail::SERVICE;
                        ChargeDetail::create($save);
                    }
                }
            }
            if (isset($params['power_children'])) {
                $params['power_children'] = json_decode($params['power_children'], true);
                foreach ($params['power_children'] as $k => $v) {
                    if (isset($v['minutes']) && isset($v['min_power']) && isset($v['max_power'])) {
                        $save = [];
                        $save['minutes'] = $v['minutes'];
                        $save['min_power'] = $v['min_power'];
                        $save['max_power'] = $v['max_power'];
                        $save['charge_option_id'] = $params['id'];
                        $save['type'] = ChargeDetail::POWER;
                        ChargeDetail::create($save);
                    }
                }
            }
            if (isset($params['time_children'])) {
                $params['time_children'] = json_decode($params['time_children'], true);
                foreach ($params['time_children'] as $k => $v) {
                    if (isset($v['fee'])) {
                        $save = [];
                        $save['type'] = ChargeDetail::FEE;
                        $save['fee'] = $v['fee'];
                        if(isset($v['minutes'])){
                            $save['minutes'] = $v['minutes'];
                        }
                        $save['charge_option_id'] = $params['id'];
                        ChargeDetail::create($save);
                    }
                }
            }
            Db::commit();
            return $this->success(['charge_option_id' => $params['id']]);
        } catch (\Exception $e) {
            Db::rollBack();
            return $this->error(code: 1003, msg: $e->getMessage() . $e->getTraceAsString());
        }
    }

}
